package CarRental;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class UserFrame extends JFrame {
    private JTable table;
    private DefaultTableModel tableModel;
    private int currentUserId; // 当前登录用户的 UserID

    public UserFrame(int userId) {
        this.currentUserId = userId; // 保存当前登录用户的 UserID

        setTitle("用户界面");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        // 创建按钮面板，并将其放置在窗口顶部
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); // 按钮左对齐

        JButton viewVehiclesButton = new JButton("查看车辆信息");
        JButton rentVehicleButton = new JButton("租车");
        JButton changeVehicleButton = new JButton("换车");
        JButton simulatePaymentButton = new JButton("模拟付款");
        JButton switchAccountButton = new JButton("切换账号"); // 新增切换账号按钮
        JButton exitButton = new JButton("退出程序"); // 新增退出按钮

        buttonPanel.add(viewVehiclesButton);
        buttonPanel.add(rentVehicleButton);
        buttonPanel.add(changeVehicleButton);
        buttonPanel.add(simulatePaymentButton);
        buttonPanel.add(switchAccountButton); // 添加切换账号按钮
        buttonPanel.add(exitButton); // 添加退出按钮

        // 创建表格
        tableModel = new DefaultTableModel();
        table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);

        panel.add(buttonPanel, BorderLayout.NORTH); // 将按钮面板放置在窗口顶部
        panel.add(scrollPane, BorderLayout.CENTER); // 将表格放置在窗口中央

        // 绑定按钮事件
        viewVehiclesButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                viewVehicles();
            }
        });

        rentVehicleButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                rentVehicle();
            }
        });

        changeVehicleButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                changeVehicle();
            }
        });

        simulatePaymentButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                simulatePayment();
            }
        });

        switchAccountButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose(); // 关闭当前窗口
                new LoginFrame().setVisible(true); // 返回登录界面
            }
        });

        exitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0); // 退出程序
            }
        });

        add(panel);
    }

    // 查看车辆信息
    private void viewVehicles() {
        tableModel.setRowCount(0); // 清空表格
        tableModel.setColumnIdentifiers(new String[]{"VehicleID", "Type", "Brand", "Color", "Rent", "Status"});

        String sql = "SELECT * FROM Vehicles";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                int vehicleId = rs.getInt("VehicleID");
                String type = rs.getString("Type");
                String brand = rs.getString("Brand");
                String color = rs.getString("Color");
                int rent = rs.getInt("Rent");
                String status = rs.getString("Status");

                tableModel.addRow(new Object[]{vehicleId, type, brand, color, rent, status});
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Error: " + e.getMessage());
        }
    }

    // 租车
    private void rentVehicle() {
        int vehicleId = Integer.parseInt(JOptionPane.showInputDialog("请输入要租用的车辆ID:"));
        String rentDateStr = JOptionPane.showInputDialog("请输入租车日期 (yyyy-MM-dd):");
        String returnDateStr = JOptionPane.showInputDialog("请输入还车日期 (yyyy-MM-dd):");

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date rentDate = dateFormat.parse(rentDateStr);
            Date returnDate = dateFormat.parse(returnDateStr);

            // 检查车辆状态
            String checkStatusSql = "SELECT Status FROM Vehicles WHERE VehicleID = ?";
            try (Connection conn = DBConnection.getConnection();
                 PreparedStatement checkStatusStmt = conn.prepareStatement(checkStatusSql)) {

                checkStatusStmt.setInt(1, vehicleId);
                ResultSet statusRs = checkStatusStmt.executeQuery();

                if (statusRs.next()) {
                    String status = statusRs.getString("Status");
                    if (!"Free".equals(status)) {
                        JOptionPane.showMessageDialog(this, "车辆ID为 " + vehicleId + " 的车辆当前不可租用。");
                        return;
                    }
                } else {
                    JOptionPane.showMessageDialog(this, "未找到车辆ID为 " + vehicleId + " 的车辆信息。");
                    return;
                }
            }

            // 计算租金总额
            long diff = returnDate.getTime() - rentDate.getTime();
            int days = (int) (diff / (1000 * 60 * 60 * 24));

            // 查询车辆租金
            String sql = "SELECT Rent FROM Vehicles WHERE VehicleID = ?";
            try (Connection conn = DBConnection.getConnection();
                 PreparedStatement pstmt = conn.prepareStatement(sql)) {

                pstmt.setInt(1, vehicleId);
                ResultSet rs = pstmt.executeQuery();

                if (rs.next()) {
                    int rentPerDay = rs.getInt("Rent");
                    int totalRent = rentPerDay * days;

                    // VIP 用户享受 8 折优惠
                    totalRent = (int) (totalRent * 0.8);

                    // 插入订单
                    sql = "INSERT INTO Orders (UserID, VehicleID, RentDate, ReturnDate, TotalRent, OrderStatus) VALUES (?, ?, ?, ?, ?, ?)";
                    try (PreparedStatement orderStmt = conn.prepareStatement(sql)) {
                        orderStmt.setInt(1, currentUserId); // 使用当前登录用户的 UserID
                        orderStmt.setInt(2, vehicleId);
                        orderStmt.setDate(3, new java.sql.Date(rentDate.getTime()));
                        orderStmt.setDate(4, new java.sql.Date(returnDate.getTime()));
                        orderStmt.setInt(5, totalRent);
                        orderStmt.setString(6, "Pending");
                        orderStmt.executeUpdate();

                        // 更新车辆状态为已租
                        sql = "UPDATE Vehicles SET Status = 'Rented' WHERE VehicleID = ?";
                        try (PreparedStatement updateStmt = conn.prepareStatement(sql)) {
                            updateStmt.setInt(1, vehicleId);
                            updateStmt.executeUpdate();
                        }

                        JOptionPane.showMessageDialog(this, "租车成功！订单已生成，总租金为: " + totalRent);
                        viewVehicles(); // 刷新车辆信息表格
                    }
                } else {
                    JOptionPane.showMessageDialog(this, "未找到车辆ID为 " + vehicleId + " 的车辆信息。");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Error: " + e.getMessage());
        }
    }

    // 换车
    private void changeVehicle() {
        int orderId = Integer.parseInt(JOptionPane.showInputDialog("请输入要换车的订单ID:"));
        int newVehicleId = Integer.parseInt(JOptionPane.showInputDialog("请输入新的车辆ID:"));

        // 检查新车辆状态
        String checkStatusSql = "SELECT Status FROM Vehicles WHERE VehicleID = ?";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement checkStatusStmt = conn.prepareStatement(checkStatusSql)) {

            checkStatusStmt.setInt(1, newVehicleId);
            ResultSet statusRs = checkStatusStmt.executeQuery();

            if (statusRs.next()) {
                String status = statusRs.getString("Status");
                if (!"Free".equals(status)) {
                    JOptionPane.showMessageDialog(this, "车辆ID为 " + newVehicleId + " 的车辆当前不可租用。");
                    return;
                }
            } else {
                JOptionPane.showMessageDialog(this, "未找到车辆ID为 " + newVehicleId + " 的车辆信息。");
                return;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Error: " + e.getMessage());
            return;
        }

        // 更新订单中的车辆ID
        String sql = "UPDATE Orders SET VehicleID = ? WHERE OrderID = ?";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, newVehicleId);
            pstmt.setInt(2, orderId);
            int rowsAffected = pstmt.executeUpdate();

            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(this, "换车成功！订单ID为 " + orderId + " 的车辆已更换为车辆ID " + newVehicleId);
                viewVehicles(); // 刷新车辆信息表格
            } else {
                JOptionPane.showMessageDialog(this, "未找到订单ID为 " + orderId + " 的订单信息。");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Error: " + e.getMessage());
        }
    }

    // 模拟付款
    private void simulatePayment() {
        int orderId = Integer.parseInt(JOptionPane.showInputDialog("请输入要支付的订单ID:"));
        String paymentMethod = JOptionPane.showInputDialog("请输入支付方式 (Credit Card, Cash):");

        // 查询订单总租金
        String sql = "SELECT TotalRent FROM Orders WHERE OrderID = ?";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, orderId);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                int totalRent = rs.getInt("TotalRent");

                // 插入支付信息
                sql = "INSERT INTO Payments (OrderID, PaymentAmount, PaymentDate, PaymentMethod) VALUES (?, ?, ?, ?)";
                try (PreparedStatement paymentStmt = conn.prepareStatement(sql)) {
                    paymentStmt.setInt(1, orderId);
                    paymentStmt.setInt(2, totalRent);
                    paymentStmt.setDate(3, new java.sql.Date(System.currentTimeMillis()));
                    paymentStmt.setString(4, paymentMethod);
                    paymentStmt.executeUpdate();

                    // 更新订单状态为已支付
                    sql = "UPDATE Orders SET OrderStatus = 'Paid' WHERE OrderID = ?";
                    try (PreparedStatement updateStmt = conn.prepareStatement(sql)) {
                        updateStmt.setInt(1, orderId);
                        updateStmt.executeUpdate();
                    }

                    JOptionPane.showMessageDialog(this, "支付成功！订单ID为 " + orderId + " 的订单已支付，支付方式为: " + paymentMethod);
                    viewVehicles(); // 刷新车辆信息表格
                }
            } else {
                JOptionPane.showMessageDialog(this, "未找到订单ID为 " + orderId + " 的订单信息。");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Error: " + e.getMessage());
        }
    }

    // 查看订单信息
    private void viewOrders() {
        tableModel.setRowCount(0); // 清空表格
        tableModel.setColumnIdentifiers(new String[]{"OrderID", "UserID", "Username", "VehicleID", "RentDate", "ReturnDate", "TotalRent", "OrderStatus"});

        String sql = "SELECT Orders.OrderID, Orders.UserID, Users.Username, Orders.VehicleID, Orders.RentDate, Orders.ReturnDate, Orders.TotalRent, Orders.OrderStatus " +
                "FROM Orders " +
                "JOIN Users ON Orders.UserID = Users.UserID";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                int orderId = rs.getInt("OrderID");
                int userId = rs.getInt("UserID");
                String username = rs.getString("Username");
                int vehicleId = rs.getInt("VehicleID");
                String rentDate = rs.getString("RentDate");
                String returnDate = rs.getString("ReturnDate");
                int totalRent = rs.getInt("TotalRent");
                String orderStatus = rs.getString("OrderStatus");

                tableModel.addRow(new Object[]{orderId, userId, username, vehicleId, rentDate, returnDate, totalRent, orderStatus});
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Error: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        new UserFrame(2).setVisible(true); // 假设当前登录用户的 UserID 为 2
    }
}
